from django.http import JsonResponse
from .models import NewsSysteam
import simplejson
import django.utils.timezone as timezone


def systeams(request):
    # 查看系统设置信息
    if request.method == 'GET':
        return systeam_list(request)
    #修改系统设置信息
    if request.method == 'PUT':
        return systeam_edit(request)

    else:
        return JsonResponse({"state": 0, "msg": "信息传递有问题"})


def systeam_list(request):
    page = request.GET.get("config")
    if page == "newssys":
        data = {}
        try:
            queryset = NewsSysteam.objects.all().values()
            data["state"] = 1
            data["data"] = list(queryset)[0]
            return JsonResponse(data)
        except Exception as e:
            return JsonResponse({"state": 0, "msg": "错误请求"})
    else:
        return JsonResponse({"state": 0, "msg": "信息传递有问题"})


def systeam_edit(request):
    try:
        info = simplejson.loads(request.body)
        print(info,  info["data"])
        try:
            queryset = NewsSysteam.objects.get(pk=1)
        except NewsSysteam.DoesNotExist:
            return JsonResponse({"state": 0, "msg": "系统错误暂不能提供服务"})
        try:
            newsdata = info["data"]
            queryset.name = newsdata['name']
            queryset.project_name = newsdata['project_name']
            queryset.description = newsdata['description']
            queryset.power = newsdata['power']
            queryset.levels = newsdata['levels']
            queryset.tag = newsdata['tag']
            queryset.store = newsdata['store']
            queryset.state = newsdata['state']
            queryset.updatad_by = newsdata['updatad_by']
            queryset.updatad_time = timezone.now()

            queryset.save()
            return JsonResponse({"state": 0, "msg": "修改成功"})
        except NewsSysteam.DoesNotExist:
            return JsonResponse({"state": 0, "msg": "数据有问题请检查"})

    except NewsSysteam.DoesNotExist:
        return JsonResponse({"state": 0, "msg": "数据格式不对"})